#coding:utf-8
#!/usr/bin/python
import urllib
from BeautifulSoup import BeautifulSoup
from sys import argv
import re



class Translate:
    def Start(self,word):
        self.word = word
        self.str1 = ''
        self._get_html_sourse()
        self._get_content()
        self.parse_li_dct_ec(self.htmlsourse)
        return self.str1
        
    def add_str(self,str2,flag=1):
        if not str2.find(r'&nbsp') == -1 and flag == 1:
            return
        if(len(self.str1)):
            self.str1 = self.str1 + '\n' + str2
        else:
            self.str1 = str2
            
    def _get_html_sourse(self):
        url = 'https://www.google.com/dictionary?aq=f&langpair=en|zh-CN&q=' + self.word + '&hl=en'
        self.htmlsourse=unicode(urllib.urlopen(url).read(),"utf-8","ignore").encode("utf-8","ignore")

    def parse_li_dct_ec(self,str1):
        soup=BeautifulSoup(str1)
        dct_eh_strs = soup.findAll("li",{"class":"dct-eh"})
        if len(dct_eh_strs):
            for each in dct_eh_strs:  
                div_dct_eh_str = soup.find("div",{"class":"dct-eh"})#may be phonetic symbol
                if div_dct_eh_str:
                    span_class_dct_tps = div_dct_eh_str.findAll("span",{"class":"dct-tp"})
                    for each_dct_tp in span_class_dct_tps:
                        tmp_tp = self._remove_tag(each_dct_tp)
                        self.add_str(tmp_tp.encode("utf-8","ignore"))
                dct_ec_strs = each.findAll("li",{"class":"dct-ec"})
                if len(dct_ec_strs):
                    for each1 in dct_ec_strs:
                        self.parse_span_partofspeech(str(each1))
                else:
                    self.parse_div_dct_em(each)
        else:#No dictionary translations were found,just print what we get
            self.add_str(self._remove_tag(soup),0)
            
        
    def parse_span_partofspeech(self,str2):
        soup1=BeautifulSoup(str2)
        part_of_speechs = soup1.find("span",{"title":"Part-of-Speech"})
        tmp = self._remove_tag(part_of_speechs)
        self.add_str(tmp)
        self.parse_div_dct_em(soup1)
    
    def parse_div_dct_em(self,soup):
        div_dct_ems = soup.findAll("div",{"class":"dct-em"})
        for each in div_dct_ems:
            #print type(self._remove_tag(each))
            self.add_str(self._remove_tag(each))

    def _get_content(self):
        root =  re.search(r'[<]div\s*?class[=]["]dct-srch-rslt["][>].*[<][/]div[>]',self.htmlsourse,re.S)
        if root:
            self.htmlsourse = root.group()
            #print root.group()
            pass

    def _remove_tag(self,tag):
        return ''.join([element  for element in tag.recursiveChildGenerator() if isinstance(element,unicode)])



#if __name__=="__main__":
#    Translate().Start()
